import { getRequest } from "./api";

export const initMenu = (router,store)=>{
    if(store.state.routes.length>0){
        return;
    }                                                                                                        
    getRequest('/menu/getMenuInfo').then(data=>{
        if(data){ 
            //格式化Router
            let formatRoutes = toFormatRoutes(data.data);
            //添加到路由
            router.addRoutes(formatRoutes);
            //将数据存入vuex
            store.commit('initRoutes',formatRoutes);
        }
    })
}

export const toFormatRoutes=(routes)=>{
    let fmtRoutes = [];
    routes.forEach(route => {
        let{
            menuName,
            path,
            component,
            icon,
            children
        }=route;
        if(children){
            //递归
            children=toFormatRoutes(children);
        } 
        let fmtRoute={
            path:path,
            name:menuName,
            icon:icon,
            children:children,
            component(resolve){
                if(component.startsWith('MyHome')){
                    require(['../views/'+component+'.vue'],resolve);
                }else if(component.startsWith('Emp')){
                    require(['../views/emp/'+component+'.vue'],resolve);
                }else if(component.startsWith('Per')){
                    require(['../views/per/'+component+'.vue'],resolve);
                }else if(component.startsWith('Sal')){
                    require(['../views/sal/'+component+'.vue'],resolve);
                }else if(component.startsWith('Sta')){
                    require(['../views/sta/'+component+'.vue'],resolve);
                }else if(component.startsWith('Sys')){
                    require(['../views/sys/'+component+'.vue'],resolve);
                }
            }
        }
        fmtRoutes.push(fmtRoute);
    });
    return fmtRoutes;
}